<template>
    <a-button type="primary" @click="bcsDetailEditTableHandler">点击编辑</a-button>
    <!-- <a-button v-if="isTableEditStatus" @click="bcsDetailSaveTableHandler">点击保存</a-button> -->
    <a-button @click="bcsDetailSaveTableHandler">点击保存</a-button>
    <!-- <a-table :columns="columns" :data-source="data" /> -->
    <a-table class="trColor"  :scroll="{x:'max-content'}"  :pagination="false"
        :row-class-name="(_record:any) => (_record.children ? `${_record.basicName}BgColor` : undefined)" :columns="yearColumns"
        :data-source="testData">
        <template #bodyCell="{ column, text, record }">
            <!-- <span>{{ column.dataIndex }}</span> -->
            <!-- <a-input v-model:value=""></a-input> -->
            <div style="display: flex; justify-content: space-between;"
                v-if="isTableEditStatus && blackList.includes(record.basicName) && column.dataIndex != 'name' && column.dataIndex != 'total' && column.dataIndex != 'operation'">
                <a-input-number style="width: 45%;"
                    v-model:value="editableData[record.basicName][column.dataIndex].Price"></a-input-number>
                <a-input-number v-if="record.basicName !== 'software_tools'" style="width: 45%;"
                    v-model:value="editableData[record.basicName][column.dataIndex].Percent"></a-input-number>
                <a-input-number v-else style="width: 45%;"
                    v-model:value="editableData[record.basicName][column.dataIndex].IrNumber"></a-input-number>
            </div>

            <a-input-number
                v-if="!blackList.includes(record.basicName) && editableData[record.basicName] && column.dataIndex != 'name' && column.dataIndex != 'total' && column.dataIndex != 'operation'"
                v-model:value="editableData[record.basicName][column.dataIndex]"
                style=" width: 100% ;margin: -5px 0"></a-input-number>
            <template v-if="!isTableEditStatus">
                <!-- {{ `测试` + column.dataIndex }} -->
                <span>{{ column.dataIndex == 'total' && record.total == -1 ? '-' : text }}</span>
                <!-- <span>{{ column.dataIndex == 'total'? '8' : text }}</span> -->
                <span v-if="record.total == -1 && column.dataIndex !== 'name' && column.dataIndex !== 'total'">%</span>
            </template>
        </template>
    </a-table>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { number, string } from 'vue-types';
import type { UnwrapRef } from 'vue';
import { cloneDeep, first, forIn } from 'lodash';
// import { cloneDeep, forIn } from 'lodash';
import { CaretDownOutlined, CaretUpOutlined, CaretRightOutlined } from '@ant-design/icons-vue';


const editableData: UnwrapRef<Record<string, any>> = reactive({});

//   单个的编辑按钮
const edit = (basicName: string) => {
    // // console.log('行号', basicName);

    for (const item of testData.value) {
        if (item.children && item.children.length > 0) {
            for (const smallItem of item.children) {
                if (smallItem.basicName === basicName) {
                    // // console.log('找到了',smallItem);
                    editableData[basicName] = cloneDeep(smallItem)
                    break;
                }
            }
            // // console.log('继续');
            if (editableData[basicName]) {
                break
            }
        }
    }

};
//   单个的保存按钮
const save = (basicName: string) => {
    // 寻找到testData中对应的对象，然后进行赋值操作
    for (const item of testData.value) {
        if (item.children && item.children.length > 0) {
            for (let smallItem of item.children) {
                // console.log('testoooo', basicName, smallItem);

                if (smallItem.basicName === basicName) {
                    // // console.log('找到了',smallItem);
                    // editableData[basicName]=cloneDeep(smallItem)
                    // smallItem = cloneDeep(editableData[basicName])
                    Object.assign(smallItem, editableData[basicName])
                    // console.log('测试成没成', smallItem);
                    delete editableData[basicName];
                    break;
                }
            }
            // // console.log('继续');
            if (!editableData[basicName]) {
                break
            }
        }
    }


    // Object.assign(testData.value.filter(item => basicName == item.basicName)[0], editableData[basicName]);

};

const cancel = (basicName: string) => {
    delete editableData[basicName];
};

// 定义变量用于控制当前的表格是否处于编辑状态
const isTableEditStatus = ref(false)

// 点击表格上的编辑时触发的回调函数
const bcsDetailEditTableHandler = () => {
    // 需要将所有的数据转存到编辑的数据结构当中
    // 这个编辑的容器中存放的时每个模块下的每条数据，也就是需要遍历所有数据，将每条数据拿来

    // console.log('打印表格的数据信息', testData.value);

    // 点击编辑的时候需要单独处理一下数据，所以还是需要调用一下数据处理函数
    // console.log('741852', strObjData.value);

    let { tableBody, tableHeader } = dealDataTest(strObjData, 'zhaoTest', true)
    yearColumns = tableHeader
    testData.value = tableBody

    testData.value.forEach((firstItem, index) => {
        if (firstItem.children && firstItem.children.length > 0) {
            firstItem.children.forEach((secondItem, idx) => {
                editableData[secondItem.basicName] = cloneDeep(secondItem)
            })
        }
    })
    // console.log(editableData);


    // 打开开关，让表格进入编辑状态
    isTableEditStatus.value = true

}

// 点击表格上方的保存时触发的回调函数
const bcsDetailSaveTableHandler = () => {
    // 保存的时候需要遍历原数组，然后将编辑的容器当中对应的某行数据的这个对象的值重新赋值给原数组
    // console.log('打印表格的数据信息', testData.value);

    testData.value.forEach((firstItem, index) => {
        if (firstItem.children && firstItem.children.length > 0) {
            firstItem.children.forEach((secondItem, idx) => {
                // editableData[secondItem.basicName] = cloneDeep(secondItem)
                secondItem = cloneDeep(editableData[secondItem.basicName])
                firstItem.children![idx] = secondItem
                // 删除编辑容器中的该对象，即删除编辑容器中的一行数据
                delete editableData[secondItem.basicName]

                // 保存的时候不需要处理成着中国格式，需要转换成后端需要的那个中形式，
                // 然后传递给后端，后端更新成功以后，再请求后端的数据，重新做展示
                if (blackList.includes(secondItem.basicName)) {
                    // console.log(secondItem);
                    for (const thirdItem in secondItem) {
                        if (Object.prototype.toString.call(secondItem[thirdItem]) === '[object Object]') {
                            if (secondItem.basicName === 'software_tools') {
                                secondItem[thirdItem] = secondItem[thirdItem].Price * secondItem[thirdItem].IrNumber
                            } else {
                                // Reflect.set(secondItem, `${bcsId}${listData.year_total[idx]}`, item.Price * item.Percent / 100)
                                secondItem[thirdItem] = secondItem[thirdItem].Price * secondItem[thirdItem].Percent / 100
                            }
                        }
                    }
                }



            })
        }
    })
    // console.log('编辑的容器', editableData);
    // console.log('原数组更改后的数据', testData.value);


    // 点了保存表格应该进入展示模式
    isTableEditStatus.value = false
}





// 需要的数据
let str = '{"year_total":[2019,2021,2022,2023],"income":{"car_output_rfq":[10000,10000,10000,10000,40000],"ir_rate_rfq":[83.5,83.5,83.5,83.5,-1],"ir_number_rfq":[8350,8350,8350,8350,33400],"car_output":[9000,9000,9000,9000,36000],"ir_rate":[83.5,83.5,83.5,83.5,-1],"ir_number":[7515,7515,7515,7515,30060],"hardware_price":[{"Price":8500,"Percent":100},{"Price":0,"Percent":100},{"Price":4000,"Percent":100},{"Price":9898,"Percent":100},{"Price":-1,"Percent":-1}],"software_price":[{"Price":0,"Percent":100},{"Price":3400,"Percent":100},{"Price":660.2475,"Percent":100},{"Price":0,"Percent":100},{"Price":-1,"Percent":-1}],"develop_one":[0,0,0,0,0],"software_service":[0,0,0,0,0],"hardware_income":[63877500,0,30060000,74383470,168320970],"software_income":[0,25551000,4961759.962499999,0,30512759.9625]},"three_cost":{"hardware_buy_price":[{"Price":0,"Percent":100},{"Price":0,"Percent":100},{"Price":0,"Percent":100},{"Price":0,"Percent":100},{"Price":-1,"Percent":-1}],"all_buy_cost":[0,0,0,0,0],"supply_developer_money":[0,0,0,0,0],"three_all_cost":[0,0,0,0,0]},"in_platform":{"ark_sw":[0,0,0,0,0],"ark_develop":[0,0,0,0,0],"software_tools":[{"Price":0,"IrNumber":7515},{"Price":0,"IrNumber":7515},{"Price":0,"IrNumber":7515},{"Price":0,"IrNumber":7515},{"Price":0,"IrNumber":0}],"ark_hardware_develop":[0,0,0,0,0],"drive_platform_price":[156,156,156,156,624],"stop_platform_price":[54,54,54,54,216],"base_drive_price":[7.1,7.1,7.1,7.1,28.4],"other_func":[0,0,0,0,0],"software_platform_dev":[1631506.5,1631506.5,1631506.5,1631506.5,6526026]},"cus_cost":{"develop_people_cost":[0,0,0,0,0],"develop_no_people_cost":[0,0,0,0,0],"cus_project_dev_cost":[0,0,0,0,0]},"over_head":{"period_fee":[0,0,0,0,0]},"over_view":{"all_sales_income":[63877500,25551000,35021759.9625,74383470,198833729.9625],"all_develop_fee":[1631506.5,1631506.5,1631506.5,1631506.5,6526026],"all_cost":[0,0,0,0,0],"tax_profit":[0,0,0,0,0],"tax_profit_percent":[0,0,0,0,-1]}}'



// 转换为对象的数据
let strObjData = JSON.parse(str)
// console.log('初始的', strObjData);

// 设置名单，即哪些是需要单独处理的
let blackList = ['hardware_price', 'software_price', 'hardware_buy_price', 'software_tools']

interface BcsDetailIncomeModel {
    car_output: number[],
    car_output_rfq: number[],
    develop_one: number[],
    hardware_income: number[],
    hardware_price: number[],// 两个待定
    software_price: number[],
    ir_number: number[],
    ir_number_rfq: number[],
    ir_rate: number[],
    ir_rate_rfq: number[],
    software_service: number[],
}
interface BcsDetailThreeCostModel {
    all_buy_cost: number[],
    hardware_buy_price: number[],  //待定
    supply_developer_money: number[],
    three_all_cost: number[]
}
interface BcsDetailInPlatformModel {
    ark_develop: number[],
    ark_hardware_develop: number[],
    supply_developer_money: number[],
    ark_sw: number[]
    base_drive_price: number[]
    drive_platform_price: number[],
    other_func: number[],
    software_platform_dev: number[],
    software_tools: number[],  // 待定
    stop_platform_price: number[],
}
interface BcsDetailCusCostModel {
    cus_project_dev_cost: number[],
    develop_no_people_cost: number[],
    develop_people_cost: number[],
}
interface BcsDetailOverViewModel {
    all_cost: number[],
    all_develop_fee: number[],
    all_sales_income: number[],
    tax_profit: number[],
    tax_profit_percent: number[],
}


// 为转换完成的数据定义数据类型的接口
interface BcsDetailTableDataModel {
    year_total: number[],
    income: BcsDetailIncomeModel,
    three_cost: BcsDetailThreeCostModel,
    in_platform: BcsDetailInPlatformModel,
    cus_cost: BcsDetailCusCostModel,
    over_head: { period_fee: number[] },
    over_view: BcsDetailOverViewModel

}

// 得到内部年份进行处理，处理成表头的格式
let yearColumns = reactive<{ title: string, dataIndex: string, key: string, fixed: boolean, align: string }[]>([])

// yearColumns = strObjData.year_total.map((item: number) => {
//   let newItem = {
//     title: item.toString(), dataIndex: 'zhaoTest' + item.toString(), key: item.toString(), fixed: false
//   }
//   return newItem
// })
// yearColumns.unshift({ title: '费用类型', dataIndex: 'name', key: '-1', fixed: false })
// yearColumns.push({ title: '总计', dataIndex: 'total', key: '-2', fixed: false })
// // console.log(yearColumns);
let index = ref(1)
let testData = ref<{
    key: number,
    name: string,
    children?: Array<any>
}[]>([])



// 定义一个函数用于处理BCS详情页面当中表格数据中的名字显示
const dealNameDataShow = (name: string) => {
    switch (name) {
        // 收入端部分
        case 'income':
            return '收入端'
        case 'car_output_rfq':
            return '车型产量(RFQ)'
        case 'ir_rate_rfq':
            return '搭载率(RFQ)'
        case 'car_output':
            return '车型产量'
        case 'ir_number_rfq':
            return '搭载量(RFQ)'
        case 'car_output':
            return '车型产量(调整)'
        case 'ir_rate':
            return '搭载率(调整)'
        case 'ir_number':
            return '搭载量(调整)'
        case 'hardware_price':
            return '硬件单价'
        case 'software_price':
            return '软件授权单价'
        case 'develop_one':
            return '开发费一次性补偿'
        case 'software_service':
            return '软件服务费'
        case 'hardware_income':
            return '硬件收入'
        case 'software_income':
            return '软件授权收入'

        // 第三方成本部分
        case 'three_cost':
            return '第三方成本'
        case 'hardware_buy_price':
            return '硬件采购单价'
        case 'all_buy_cost':
            return '总硬件采购成本'
        case 'supply_developer_money':
            return '供应商开发费'
        case 'three_all_cost':
            return '第三方总成本'

        // 内部平台部分 
        case 'in_platform':
            return '内部平台'
        case 'ark_sw':
            return 'ARK SW工具链分摊'
        case 'ark_develop':
            return 'ARK研发人员分摊'
        case 'software_tools':
            return '软件工具授权费'
        case 'ark_hardware_develop':
            return 'ARK硬件平台开发平摊费'
        case 'drive_platform_price':
            return '行车平台软件分摊单价'
        case 'stop_platform_price':
            return '泊车平台软件分摊单价'
        case 'base_drive_price':
            return '基础行车功能分摊单价'
        case 'other_func':
            return '其他功能分摊'
        case 'software_platform_dev':
            return '软件平台开发分摊费'

        // 客户项目研发成本部分
        case 'cus_cost':
            return '客户项目研发成本'
        case 'develop_people_cost':
            return '研发人力成本'
        case 'develop_no_people_cost':
            return '研发非人力成本'
        case 'cus_project_dev_cost':
            return '客户项目研发成本'

        // 期间成本部分
        case 'over_head':
            return '期间成本'
        case 'period_fee':
            return '期间费用'

        // 核算总览部分
        case 'over_view':
            return '核算总览'
        case 'all_develop_fee':
            return '总研发费用'
        case 'all_sales_income':
            return '总销售收入'
        case 'all_cost':
            return '总成本'
        case 'tax_profit':
            return '息税前利润'
        case 'tax_profit_percent':
            return '息税前利润百分比'
        default:
            return '未知'
    }
}

// 处理第一层数据的函数
const getDealFirstData = (data: any) => {
    let firstArr = []
    for (const firstItem in data) {
        console.log('一层的名字', firstItem);
        if (firstItem == 'year_total') continue
        let firstItemObj: {
            key: number,
            name: string,
            basicName: string
            children: object
        } = {
            key: 1,
            name: '',
            basicName: '',
            children: {}
        }

        firstItemObj.basicName = firstItem
        firstItemObj.name = dealNameDataShow(firstItem)
        firstItemObj.key = index.value++
        Object.assign(firstItemObj.children, data[firstItem])

        firstArr.push(firstItemObj)
    }
    console.log(firstArr);


    return firstArr
}

// 处理第二层数据的函数
const getDealSecondData = (data: any) => {
    console.log('12345');
    data.forEach((item:any) => {
        for (const secondItem in item.children) {
            console.log('第二层的名字', secondItem);

        }
    });

}
// 处理其他的大部分数据
const dealDataTest = (listData: any, bcsId: string, isEdit: boolean = false) => {

    let tableColumns: {
        title: string, dataIndex: string, key: string, fixed: boolean, align: string
    }[] = []
    /**
     * 处理表头数据
     */
    tableColumns = listData.year_total.map((item: number) => {
        let newItem = {
            title: item.toString(), dataIndex: bcsId + item.toString(), key: item.toString(), fixed: false, align: 'center'
        }
        return newItem
    })
    tableColumns.unshift({ title: '费用类型', dataIndex: 'name', key: '-1', fixed: false, align: 'left' })
    tableColumns.push({ title: '总计', dataIndex: 'total', key: '-2', fixed: false, align: 'center' })
    tableColumns.push({ title: '操作', dataIndex: 'operation', key: '-3', fixed: false, align: 'center' })

    /**
     * 下边处理的是表格提数据
     */
    // 处理数据，
    let firstArr = []
    // 遍历的是最大的对象
    console.log("打印的最外层的对象", listData);

    // firstArr = listData.map(itemArea=>{
    //     // console.log(itemArea);

    //     return itemArea
    // })
    // console.log(firstArr);


    for (const itemArea in listData) {
        // // console.log('test', itemArea);
        if (itemArea === 'year_total') continue
        // // console.log('test', itemArea);
        let secondObj: {
            key: number,
            name: string,
            basicName: string
            children: Array<any>
        } = {
            key: 1,
            name: '',
            basicName: '',
            children: []
        }
        secondObj.name = dealNameDataShow(itemArea)
        secondObj.basicName = itemArea
        secondObj.key = index.value++
        // 遍历的是每部分的那个对象，其中的每项是一个数组
        for (const smallItem in listData[itemArea]) {
            let thirdObj: {
                key: number,
                name: string,
                basicName: string
            } = {
                key: 1,
                name: '',
                basicName: '',
            }
            thirdObj.name = dealNameDataShow(smallItem)
            thirdObj.basicName = smallItem
            thirdObj.key = index.value++
            listData[itemArea][smallItem].forEach((item: any, idx: number) => {
                if (idx <= listData.year_total.length - 1) {
                    if (Object.prototype.toString.call(item) === '[object Object]' && !isEdit) {
                        // // console.log('对象的名字', thirdObj.basicName);

                        // 如果碰到的数据为对象格式的，那就要区分是在编辑也米娜还是处于展示页面当中
                        // 如果处于展示页面当中那就需要得到乘积进行展示，相反就不需要处理

                        if (thirdObj.basicName === 'software_tools') {
                            Reflect.set(thirdObj, `${bcsId}${listData.year_total[idx]}`, item.Price * item.IrNumber)
                        } else {
                            Reflect.set(thirdObj, `${bcsId}${listData.year_total[idx]}`, item.Price * item.Percent / 100)
                        }
                    } else {
                        Reflect.set(thirdObj, `${bcsId}${listData.year_total[idx]}`, item)
                    }
                } else {
                    if (Object.prototype.toString.call(item) === '[object Object]') {
                        if (thirdObj.basicName === 'software_tools') {
                            Reflect.set(thirdObj, `total`, item.Price * item.IrNumber)
                        } else {
                            if (Object.values(item).every(itnum => itnum === -1)) {
                                Reflect.set(thirdObj, `total`, '-')
                            } else {
                                Reflect.set(thirdObj, `total`, item.Price * item.Percent / 100)
                            }
                        }
                    } else {
                        Reflect.set(thirdObj, 'total', item)
                    }
                }
            })
            secondObj.children.push(thirdObj)
        }
        firstArr.push(secondObj)
    }
    console.log('处理结果', firstArr, tableColumns);

    return { tableBody: firstArr, tableHeader: tableColumns }
}

// 定义数据反转处理的函数，保存的时候需要这个函数将数据处理为后端所需要的数据
const reversalDealTableData = (tableHeader: any, tableBody: any, bcsId: string,) => {
    let dealSuccessData = {}
    // 先处理年份信息
    let year_total = tableHeader.filter((item:any) => {
        return item.dataIndex != 'name' && item.dataIndex != 'total' && item.dataIndex != 'operation'
    }).map((itemYearObj:any) => {
        return Number(itemYearObj.title)
    })
    // console.log('处理好的年份信息',year_total);
    // 将数据存入对象当中
    Object.assign(dealSuccessData, 'year_total', year_total)
    // console.log('后端需要的对象',dealSuccessData);


    // 处理表格体数据
    tableBody.forEach((itemArea:any) => {
        // console.log(itemArea);

        let secondObj = {}
        if (itemArea.children && itemArea.children.length > 0) {
            itemArea.children.forEach((secondItem:any) => {
                // console.log('zhecengshuju',secondItem);
                let thirdArr = []
                // 循环年份，得到每年的数据，以及总数
                for (const itemYear of year_total) {
                    thirdArr.push(secondItem[bcsId + itemYear])
                }
                thirdArr.push(secondItem.total)
                // console.log('每条数据',thirdArr);

                // Reflect.set()
                Reflect.set(secondObj, secondItem.basicName, thirdArr)
            });
            // console.log('每部分中的数据',secondObj);
            Reflect.set(dealSuccessData, itemArea.basicName, secondObj)

        }

    });
    // console.log('拼接好的整体数据',dealSuccessData);
    // console.log(JSON.stringify(dealSuccessData));

    return JSON.stringify(dealSuccessData)


}

onMounted(() => {
    // console.log('原始数据', strObjData);

    let { tableBody, tableHeader } = dealDataTest(strObjData, 'zhaoTest')
    testData.value = tableBody
    yearColumns = tableHeader
    
    let mapData = new Map(Object.entries(strObjData))
    
    console.log('使用map存储的对象',mapData)
    for (let [key,value] of mapData) {
        console.log('map数据中的每一项',key,value);
        if (key=='year_total') {
            
        }else{
            let secondMap = Object.entries(value)
            console.log('打印secondMap',secondMap);
            
            for (const [secondKey,secondValue] of secondMap) {
                console.log('二层的数据',secondKey,secondValue);
                
            }
        }
    }
    

    // console.log('***//122222/***', yearColumns);
    // console.log('***///***', testData.value);
    // console.log('/////////////////////////////////////////////////');
    // reversalDealTableData(yearColumns,tableBody, 'zhaoTest')

    // let firstArray = getDealFirstData(strObjData)
    // getDealSecondData(firstArray)

})


</script>